package com.user.handle;

import com.user.comment.KeyStr;
import com.user.config.JwtProperties;
import com.user.entity.Payload;
import com.user.entity.UserInfo;
import com.user.util.JedisUtil;
import com.user.util.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

public class LogoutHandler implements LogoutSuccessHandler {
    private JwtProperties properties;
    public LogoutHandler(JwtProperties properties){
        this.properties =properties;
    }
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String authorization = request.getHeader("Authorization");
        if(!StringUtils.isBlank(authorization)){
            Payload<UserInfo> infoFromToken = JwtUtils.getInfoFromToken(authorization, properties.getPublicKey());
            Date expiration = infoFromToken.getExpiration();
            Date date = new Date();
            long time = expiration.getTime() - date.getTime();
            if (time >= KeyStr.LOG_OUT_TIME){
                Jedis jedis = JedisUtil.getJedis();
                String id = infoFromToken.getId();
                jedis.set(KeyStr.OUT_TOKET+id,authorization,"NX","PX",time);
                JedisUtil.close(jedis);
            }
        }
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/text;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print("{'message':'登出成功'}");
        writer.flush();
        writer.close();
    }
}
